var express = require('express');
var routes = require('./routes')
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session')
var bodyParser = require('body-parser');
var app = express();

// 设置模板路径
app.set('views', path.join(__dirname, 'application/views'));
app.set('view engine', 'ejs');
// 设置静态文件路径
app.use(express.static(path.join(__dirname, 'public')));

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
	extended: false
}));
app.use(cookieParser());
app.use(session({
	secret: 'nodetestapp', //secret的值建议使用随机字符串
	resave: false,
	saveUninitialized: true,
	cookie: {
//		secure: true,
		maxAge: 60 * 1000 * 30 // 过期时间（毫秒）
	} 
}))

// 设置路由
app.use('/', require('./routes/home/home'));
app.use('/index', require('./routes/home/home'));
app.use('/admin', require('./routes/admin/admin'));
app.use('/api', require('./routes/api/api'));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
	var err = new Error('Not Found');
	err.status = 404;
	next(err);
});

// error handler
app.use(function(err, req, res, next) {
	// set locals, only providing error in development
	res.locals.message = err.message;
	res.locals.error = req.app.get('env') === 'development' ? err : {};
	// render the error page
	res.status(err.status || 500);
	res.render('error');
});

//设置跨域访问
app.all('*', function(req, res, next) {
	res.header('Access-Control-Allow-Origin', '*');
	res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
	res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

	if(req.method == 'OPTIONS') {
		res.send(200);
	} else {
		next();
	}
});

module.exports = app;
console.log("server running in localhost:3000")